package com.xiyu.service.service.infra.webHook;

import cn.hutool.core.util.StrUtil;
import com.xiyu.service.framework.mail.sync.SyncWebhookInfo;
import com.xiyu.service.model.market.setting.MarketSettingDomain;
import com.xiyu.service.model.market.task.*;
import com.xiyu.service.repository.market.setting.MarketSettingDomainRepository;
import com.xiyu.service.repository.market.task.MarketTaskReceiverRepository;
import com.xiyu.service.repository.market.task.MarketTaskRepository;
import com.xiyu.service.repository.market.task.MarketTaskWebhookLogRepository;
import com.xiyu.service.vo.infra.sendCloud.SendCloudReceiveInput;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import com.xiyu.service.util.entity.EntityUtils;
import com.xiyu.service.framework.web.web.core.pojo.PageResult;
import com.xiyu.service.convert.infra.webHook.SendCloudConvert;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;

/**
 * sendCloud Service 实现类
 */
@Service
@Validated
public class SendCloudServiceImpl implements SendCloudService {


    @Resource
    MarketSettingDomainRepository marketSettingDomainRepository;

    @Resource
    MarketTaskWebhookLogRepository marketTaskWebhookLogRepository;

    @Resource
    MarketTaskReceiverRepository marketTaskReceiverRepository;

    @Resource
    MarketTaskRepository marketTaskRepository;

    @Resource
    SyncWebhookInfo syncWebhookInfo;


    @Override
    public String receive(SendCloudReceiveInput inputVO) {
        if (inputVO == null) {
            return  "消息为空";
        }

        // 1.验证签名
        MarketSettingDomain domain = marketSettingDomainRepository.findByApiUser(inputVO.getApiUser()).orElse(null);
        if(domain == null){
           return errorLog(inputVO, "找不到发信域名");
        }
        try {
            String signature = inputVO.getSignature();
            String appKey = "xtccvcb1-f0gy-8s4q-oz7i-2liya295p2";
            String token = inputVO.getToken();
            long timestamp = inputVO.getTimestamp();
            if (!verify(appKey, token, timestamp, signature)) {
                return errorLog(inputVO, "数据签名错误");
            }
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            return errorLog(inputVO, "数据签名未知错误：" + e.getMessage());
        }

        // 2. 异步保存消息
        syncWebhookInfo.saveWebhookInfo(inputVO);
        return "";
    }

    private String errorLog(SendCloudReceiveInput inputVO, String error){
        if(inputVO != null){
            MarketTaskWebhookLog log = MarketTaskWebhookLogDraft.$.produce(draft -> draft
                    .setApiUser(inputVO.getApiUser()).setErrorMessage(StrUtil.sub(error, 0, 1024))
                    .setEvent(inputVO.getEvent()).setRequest(inputVO.toString())
            );
            marketTaskWebhookLogRepository.insert(log);
        }

        return error;
    }

    private boolean verify(String appKey, String token, long timestamp, String signature)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Mac sha256HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(appKey.getBytes(),
                "HmacSHA256");
        sha256HMAC.init(secretKey);
        String signatureCal = new String(Hex.encodeHex(sha256HMAC
                .doFinal((timestamp + token).getBytes())));
        return signatureCal.equals(signature);
    }

}
